package groupb6.shopsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import groupb6.shopsystem.mapper.ProductMapper;
import groupb6.shopsystem.mapper.ShoppingBagMapper;
import groupb6.shopsystem.pojo.entity.Product;
import groupb6.shopsystem.pojo.entity.ShoppingBag;
import groupb6.shopsystem.pojo.form.AddCartForm;
import groupb6.shopsystem.service.CustomerProductService;
import groupb6.shopsystem.util.JWTUtil;
import groupb6.shopsystem.util.enums.ResponseEnum;
import groupb6.shopsystem.util.response.ResponseException;
import groupb6.shopsystem.util.response.UniversalResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CustomerProductServiceImpl implements CustomerProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ShoppingBagMapper shoppingBagMapper;
    /*
     * 根据id查询商品
     * @author:zhangyn
     * */
    @Override
    public Product getProductDetailById(Integer id) {
        return productMapper.selectById(id);
    }

    @Override
    public UniversalResponse<?> addProIntoCart(AddCartForm addCartForm) {
        if (addCartForm.getProductId() == null || addCartForm.getNumber() == null) {
            throw new ResponseException(ResponseEnum.PARAM_IS_BLANK.getCode(), ResponseEnum.PARAM_IS_BLANK.getMsg());
        }
        LambdaQueryWrapper<ShoppingBag> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingBag::getProductId,addCartForm.getProductId())
                .eq(ShoppingBag::getBuyerId,JWTUtil.getCurrentUser().getId());
        try{
            ShoppingBag shoppingBag=shoppingBagMapper.selectList(wrapper).get(0);
            shoppingBag.setNumber(shoppingBag.getNumber()+addCartForm.getNumber());
            shoppingBagMapper.update(shoppingBag,wrapper);
        }catch (RuntimeException e){
            ShoppingBag shoppingBag = new ShoppingBag();
            shoppingBag.setBuyerId(JWTUtil.getCurrentUser().getId());
            shoppingBag.setProductId(addCartForm.getProductId());
            shoppingBag.setNumber(addCartForm.getNumber());
            shoppingBagMapper.insert(shoppingBag);
        }


        return new UniversalResponse<>(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg());
    }
}
